package com.crack.nga2.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.Xml;
import android.view.View;
import android.widget.AdapterView;

import com.crack.nga2.R;
import com.crack.nga2.custom.HeadLayoutImpl;
import com.crack.nga2.custom.PullListView;
import com.crack.nga2.custom.StatusBarCompat;
import com.crack.nga2.db.DBHelper;
import com.crack.nga2.entity.SubForum;
import com.crack.nga2.fragment.ForumFragment;
import com.crack.nga2.fragment.NavigationFragment;
import com.crack.nga2.fragment.SubForumFragment;
import com.crack.nga2.service.InternetStateService;
import com.crack.nga2.span.ImageSpanWrapper;
import com.crack.nga2.span.SpanUtil;
import com.crack.nga2.utils.GlobalConst;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class MainActivity extends AppCompatActivity implements NavigationFragment.SelectCallBacks,
        FragmentCallBacks {
    /**
     * activity的layout
     */
    private DrawerLayout drawerLayout;
    /**
     * 侧滑导航视图
     */
    private View navigation;
    /**
     * 导航Fragment
     */
    private NavigationFragment navigationFragment;
    /**
     * 用于切换主窗体内容
     */
    private FragmentManager manager;
    private ForumFragment fragment;
    private Handler mHandler = new Handler();


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        startService(new Intent(this, InternetStateService.class));
        initGlobalConst();
        setContentView(R.layout.activity_main);
//        initGlobalConst();
        drawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
        navigation = findViewById(R.id.navigation_drawer);
        navigationFragment = (NavigationFragment) (manager = getSupportFragmentManager()).findFragmentById(R.id.navigation_drawer);
        //获取导航栏列表内容，并传入导航栏
        String[] strings = getResources().getStringArray(R.array.navigation);
        navigationFragment.setDrawerList(strings);
        fragment = new ForumFragment();
        getSupportFragmentManager().beginTransaction().replace(R.id.container, fragment).commit();
        getData();
        if (!GlobalConst.isLogin) {
            drawerLayout.openDrawer(GravityCompat.START);
        }
    }

    private void getData() {
        new Thread() {
            @Override
            public void run() {
                try {
                    InputStream is = getResources().getAssets().open("forums.xml");
                    final Map<String, List<SubForum>> map = pause(is);
                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            fragment.setForumMap(map);
                        }
                    });
                } catch (IOException | XmlPullParserException e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }

    //解析数据
    @Nullable
    private Map<String, List<SubForum>> pause(InputStream is) throws XmlPullParserException, IOException {
        XmlPullParser parser = Xml.newPullParser();
        parser.setInput(is, "GBK");
        int eventType = parser.getEventType();
        Map<String, List<SubForum>> map = null;
        List<SubForum> list = null;
        //区域名称
        String string;
        //标签名称
        String tag;
        //论坛对象
        SubForum forum = null;
        while (eventType != XmlPullParser.END_DOCUMENT) {
            switch (eventType) {
                case XmlPullParser.START_DOCUMENT:
                    map = new HashMap<>();
                    break;
                case XmlPullParser.START_TAG:
                    tag = parser.getName();
                    if (tag.equals("category")) {
                        string = parser.getAttributeValue(1);
                        list = new ArrayList<>();
                        if (map != null && string != null) {
                            map.put(string, list);
                        }
                    } else if (tag.equals("forum")) {
                        if (forum == null) {
                            forum = new SubForum();
                        }
                        int fid = Integer.parseInt(parser.getAttributeValue(0));
                        String name = parser.getAttributeValue(1);
                        if (parser.getAttributeCount() == 3) {
                            String info = parser.getAttributeValue(2);
                            forum.setInfo(info);
                        }
                        forum.setFid(fid);
                        forum.setName(name);
                    }
                    break;
                case XmlPullParser.END_TAG:
                    tag = parser.getName();
                    if (tag.equals("category")) {
                        list = null;
                    } else if (tag.equals("forum")) {
                        if (list != null & forum != null) {
                            list.add(forum);
                            forum = null;
                        }
                    }
                    break;
            }
            eventType = parser.next();
        }
        is.close();
        if (map != null) {
            DBHelper helper = new DBHelper(this);
            List<SubForum> collect_forums = helper.queryForumAll();
            map.put("我的收藏", collect_forums);
            Log.i("collect", collect_forums.toString());
        }
        return map;
    }

    @Override
    public void onBackPressed() {
        if (drawerLayout.isDrawerOpen(GravityCompat.START)) {
            drawerLayout.closeDrawer(GravityCompat.START);
            return;
        }
        super.onBackPressed();
    }

    /**
     * 点击标题栏
     *
     * @param v 点击view
     */
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.drawer_toggle:
                if (!drawerLayout.isDrawerOpen(GravityCompat.START)) {
                    drawerLayout.openDrawer(GravityCompat.START);
                } else {
                    drawerLayout.closeDrawer(GravityCompat.START);
                }
                break;
            case R.id.action_search:
                //TODO
                break;
        }
    }

    /**
     * 侧滑导航栏按钮点击事件
     */
    public void doClick(View view) {
        switch (view.getId()) {
            case R.id.head_photo:
            case R.id.head_tv_name:
                if (GlobalConst.isLogin) {
                    return;
                }
                Intent intent = new Intent(this, LoginActivity.class);
                startActivityForResult(intent, 1);
                break;
            case R.id.head_user_center:
                //用户中心
                intent = new Intent(this, UserCenterActivity.class);
                startActivityForResult(intent, 2);
                break;
            case R.id.head_user_remind:
                //提醒
                intent = new Intent(this, RemindActivity.class);
                startActivity(intent);
                break;
            case R.id.head_user_message:
                //短信
                intent = new Intent(this, MessageActivity.class);
                startActivity(intent);
                break;
        }
    }

    /**
     * 点击侧滑导航栏listView点击事件
     *
     * @param parent   listView
     * @param view     点击的item
     * @param position 点击的position
     */
    @Override
    public void selectItem(AdapterView<?> parent, View view, int position) {
        Intent intent;
        switch (position) {
            case 0:
                drawerLayout.closeDrawer(GravityCompat.START);
                break;
            case 1:
                //任务
                break;
            case 2:
                //商店

                break;
//            case 3:
//                //组队
//                break;
//            case 4:
//                //扫码
//                break;
            case 3:
                //设置
                intent = new Intent(this, SettingActivity.class);
                startActivity(intent);
                break;
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //从登陆页面返回
        if (requestCode == 1 && resultCode == 1) {
            navigationFragment.initUserInfo();
        }
        //从用户中心返回并退出登陆
        if (requestCode == 2 && resultCode == 2) {
            navigationFragment.quite();
        }
    }


    @Override
    public void startActivityForResult(Intent intent, int requestCode, Bundle options) {
        super.startActivityForResult(intent, requestCode, options);
        overridePendingTransition(R.anim.base_slide_right_in,R.anim.base_slide_right_out);
    }


    /**
     * 长按收藏/取消收藏
     */
    @Override
    public boolean clickLongForum(AdapterView<?> parent, View view, int position, long id) {
        final SubForum forum = (SubForum) parent.getItemAtPosition(position);
        final DBHelper helper = new DBHelper(this);
        final boolean flag = helper.isExists(forum.getFid(), DBHelper.DB_FORUM);
        String title = flag ? "是否取消收藏" : "是否加入收藏";
        new AlertDialog.Builder(this).setTitle(title)
                .setPositiveButton("确认", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (flag) {
                            helper.delete(forum);
                            fragment.removeCollect(forum);
                        } else {
                            helper.add(forum);
                            fragment.addCollect(forum);
                        }
                    }
                }).setNegativeButton("取消", null).show();
        return true;
    }


    /**
     * 点击进入论坛
     */
    @Override
    public void clickForum(AdapterView<?> parent, View view, int position, long id) {
        SubForum forum = (SubForum) parent.getItemAtPosition(position);
        Intent intent = new Intent(this, ForumActivity.class);
        intent.putExtra("forum", forum);
        startActivityForResult(intent, 3);
    }


    /**
     * 下拉刷新事件
     */
    @Override
    public void pullDownToRefresh(int index, SubForumFragment fragment) {
        fragment.addForumList(new ArrayList<SubForum>());
    }

    /**
     * 初始化全局变量
     */
    private void initGlobalConst() {
        SpanUtil.collapseDrawable = getResources().getDrawable(R.drawable.collapsed_no);
        SpanUtil.collapseDrawable.setBounds(0, 0, 40, 40);
        SpanUtil.listDrawable = getResources().getDrawable(R.drawable.diandian_on);
        SpanUtil.listDrawable.setBounds(0, 0, 20, 20);
        SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
        String[] options = getResources().getStringArray(R.array.settings);
        for (int i = 1; i <= 7; i++) {
            String item = options[i];
            boolean b = sp.getBoolean(item, false);
            GlobalConst.settings.put(item, b);
        }
        DisplayMetrics outMetrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(outMetrics);
        GlobalConst.SCREEN_WIDTH = outMetrics.widthPixels;
        GlobalConst.SCREEN_HEIGHT = outMetrics.heightPixels;
        PullListView.MAX_HEIGHT = GlobalConst.SCREEN_HEIGHT / 6;
        HeadLayoutImpl.WIDTH = GlobalConst.SCREEN_WIDTH;

//        readLoginCookie();


        ImageSpanWrapper.defaultDrawable = getResources().getDrawable(R.drawable.loading_img);
        ImageSpanWrapper.failDrawable = getResources().getDrawable(R.drawable.default_pic);
        setDrawable(ImageSpanWrapper.defaultDrawable);
        ImageSpanWrapper.failDrawable.setBounds(0, 0, 150, 120);
    }
    private void setDrawable(Drawable drawable) {
        int width = drawable.getIntrinsicWidth();
        int height = drawable.getIntrinsicHeight();
        float f = width * 1.0f / GlobalConst.SCREEN_WIDTH;
        height = (int) (height * 1.0 / f);
        width = GlobalConst.SCREEN_WIDTH;
        drawable.setBounds(0, 0, width, height);
    }
}
